import styles from './Home.module.css'
import ScreenSaver from '../../components/ScreenSaver'
import BlogList from '../../components/BlogList'
import Footer from '../../components/Footer'
import Loading from '../../components/Loading'
import { useState, useEffect } from 'react'

function Home() {
  const [ isPending, setIsPending ] = useState(true)
  const [ error, setError ] = useState(null)
  const [ data, setData ] = useState([])
  const [ newData, setNewData ] = useState([])
  const abortController = new AbortController()
  useEffect(() => {
    getData("http://localhost:3003/articles?offset=0")
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])
  const getData = async (url) => {
    try {
      const response = await fetch(url, {signal: abortController.signal})
      const result = await response.json()
      setNewData(result)
      setData(prev => prev.concat(result))
    } catch (error) {
      setError(error.message)
    }
    setIsPending(false)
  }
  return (
    <div className={styles.home}>
      <ScreenSaver />
      <div className={styles.main}>
        { isPending && <Loading /> }
        { error && <div>{error}</div> }
        { !isPending && <BlogList blogs={data}/> }
        {
          newData.length >= 5 ? 
          (<button className={styles.more} onClick={()=>getData("http://localhost:3003/articles?offset=" + data.length)}>加载更多</button>): null
        }
      </div>
      <Footer />
    </div>
  )
}

export default Home
